<?php

namespace App\Http\Controllers;

use Exception;
use App\Models\Task;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;
use App\Http\Requests\Task\StoreTaskResource;
use App\Http\Requests\Task\UpdateTaskResource;
use App\Http\Requests\Task\DestroyTaskResource;
use App\Http\Requests\Task\QueryTaskCollection;

class TasksController extends Controller
{
	/**
	 * 获取任务数据集合
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param QueryTaskCollection $request
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function index(QueryTaskCollection $request)
    {
        // 分页数
        $paginate = $request->get('paginate', 10);
        // 名称
        $name = $request->get('name');
        // 类型名称
        $type = $request->get('type');
        // 是否必填
        $required = $request->get('required');
        // 是否拍照
        $photo = $request->get('photo');
        // 分类id
        $category_id = $request->get('category_id');
        // 获取关联信息
        $relation = $request->get('relation');
        // 是否不分页
        $is_page = $request->get('is_page');
        // 是否有效
        $effective = $request->get('effective');


        $query = Task::query();

        //加载关联模型
        if ($relation) {
			$query = $query->with($relation);
		}

        if($name){
            $query->where('name','like','%'.$name.'%');
        }

        if($type){
            $query->where('type',$type);
        }

        if($required){
            $query->where('required', true);
        }

        if($photo){
            $query->where('photo',true);
        }

        // 是否有效
        if($effective){
            $query->orWhere(function($query){
                $query->whereNull('start_time');
                $query->whereNull('end_time');
            });
            $query->orWhere(function($query){
                $time = date('Y-m-d H:i:s');
                $query->where('start_time', '<=', $time);
                $query->where('end_time', '>=', $time);
            });
        }

        if($category_id){
            $query->whereHas('categorys',function ($query) use($category_id) {
                $query->where('id',$category_id);
            });
        }

        $query->orderBy('created_at','desc');

        if($is_page == 1){
            return $this->success($query->get());
        }else{
            return $this->success($query->paginate($paginate));
        }
    }


	/**
	 * 创建任务
	 *
	 * Date: 2018/2/2
	 * @author George
	 * @param StoreTaskResource $request
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
    public function store(StoreTaskResource $request)
    {
        $task = new Task();

        $attributes = $this->validate($request, [
            'name'     => 'required',
            'required' => [
                'required',
                Rule::in([0,1]),
            ],
            'photo'    => [
                'required',
                Rule::in([0,1]),
            ],
            'type'     => [
                'required',
                Rule::in(['number', 'text', 'select', 'date', 'branch']),
            ],

        ],[
            'type.required'     => '请选择类型',
            'required.in'       => '值不是规定的值',
            'required.required' => '请选择是否必填',
            'photo.in'          => '值不是规定的值',
            'name.required'     => '参数名称不能为空',
            'type.in'           => '类型不是规定的类型',
            'photo.required'    => '请选择图片是否必填',

        ]);


        // 判断是否验证选择器值
        if($attributes['type'] == 'select'){
            $attributess = $this->validate($request, [
                'params'     => 'required|json',
            ],[
                'params.required' => '选择器值不能未空',
                'params.json'     => '不是一个正确的json格式',
            ]);
            foreach ($attributess as $k => $v){
                $task->{$k} = $v;
            }
        }


        foreach ($attributes as $k => $v){
            $task->{$k} = $v;
        }

        // 开始时间
        if($request->start_time != ""){
            $task->start_time = $request->start_time;
        }

        // 结束时间
        if($request->end_time != ""){
            $task->end_time = $request->end_time;
        }

        // 选择器内容
        $task->saveOrFail();

        // 判断是否存入分类
        if(count($request->categorys) > 0){
            // 存入数据库
            $task->categorys()->attach($request->categorys);
        }

        return $this->stored($task);
    }

	/**
	 * 根据ID获取任务信息
	 *
	 * Date: 2018/2/3
	 * @author George
	 * @param Task $task
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function show(Task $task)
    {
        return $this->success($task->with('categorys')->first());
    }


	/**
	 * 更新任务信息
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param UpdateTaskResource $request
	 * @param Task $task
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Throwable
	 */
    public function update(UpdateTaskResource $request, Task $task)
    {
        $attributes = $this->validate($request, [
            'name'     => 'required',
            'required' => [
                'required',
                Rule::in([0,1]),
            ],
            'photo'    => [
                'required',
                Rule::in([0,1]),
            ],
            'type'     => [
                'required',
                Rule::in(['number', 'text', 'select', 'date', 'branch']),
            ],
			'start_time' => 'nullable',
			'end_time' => 'nullable'
        ],[
            'type.required'     => '请选择类型',
            'required.in'       => '值不是规定的值',
            'required.required' => '请选择是否必填',
            'photo.in'          => '值不是规定的值',
            'name.required'     => '参数名称不能为空',
            'type.in'           => '类型不是规定的类型',
            'photo.required'    => '请选择图片是否必填',

        ]);


        // 判断是否验证选择器值
        if($attributes['type'] == '选择器'){
            $attributess = $this->validate($request, [
                'params'     => 'required|json',
            ],[
                'params.required' => '选择器值不能未空',
                'params.json'     => '不是一个正确的json格式',
            ]);
            foreach ($attributess as $k => $v){
                $task->{$k} = $v;
            }
        }

        foreach ($attributes as $k => $v){
            $task->{$k} = $v;
        }

        // 选择器内容
        $task->saveOrFail();

        return $this->updated($task);
    }

	/**
	 * 任务添加分类
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param Task $task
	 * @param Category $category
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function task_add_category(Task $task, Category $category){
        try {
            $task->categorys()->attach($category->id);
            return $this->success($task->categorys);
        } catch (Exception $e) {
            return $this->failed("添加失败");
        }
    }

	/**
	 * 任务删除分类
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param Task $task
	 * @param Category $category
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function task_delete_category(Task $task, Category $category){
        try {
            $task->categorys()->detach($category->id);
            return $this->success($task->categorys);
        } catch (Exception $e) {
            return $this->failed("删除失败");
        }
    }

	/**
	 * 删除任务信息
	 *
	 * Date: 2018/2/28
	 * @author George
	 * @param DestroyTaskResource $request
	 * @param Task $task
	 * @return \Illuminate\Http\JsonResponse
	 * @throws \Exception
	 */
    public function destroy(DestroyTaskResource $request, Task $task)
    {
        // 删除任务的所有分类
        $task->categorys()->detach();
        // 删除任务
        $task->delete();
        return $this->deleted();
    }
}
